<template>
    <div id='displaydiv' ref="display"></div>
</template>

<script setup>  

// const props = defineProps({
//     /**内容 */
//     code: {
//         type: [String],
//         default: ''
//     },

import { createTextVNode } from "vue";

// })
let code = ref('')
let display = ref(null)
let newcomponent = ref({
    html: "",
    js: "",
    css: "",
    component: null
})

let getSource = (source, type) => {
    let regex = new RegExp(`<${type}[^>]*>`);
    source = source.value ?? source
    let openingTag = source.match(regex);

    if (!openingTag) return "";
    else openingTag = openingTag[0];

    return source.slice(
        source.indexOf(openingTag) + openingTag.length,
        source.lastIndexOf(`</${type}>`)
    );
}
//分割代码
let splitCode = () => {
    newcomponent.value.js = getSource(code, "script")
    //vue2
    if (newcomponent.value.js.indexOf('export default') > 0)
        newcomponent.value.js = newcomponent.value.js.replace(
            /export default/,
            "return "
        );
    //语法糖
    if (newcomponent.value.js.indexOf('setup') > 0)
        newcomponent.value.js = 'return {' + newcomponent.value.js + '}'

    newcomponent.value.css = getSource(code, "style");
    newcomponent.value.html = getSource(code, "template");
    //'<div id="codeRoot" style=" width:750px; height:550px;">' + this.getSource(code, "template") + "</div>";
}
//挂载
let renderCode = (_code) => {
    //console.log(22, createTextVNode(code));
    code.value = _code
    splitCode();

    if (newcomponent.value.html !== "" && newcomponent.value.js !== "") {
        const parseStrToFunc = new Function(newcomponent.value.js)();
        console.log(newcomponent.value);
        parseStrToFunc.template = newcomponent.value.html;

        const app = createApp(parseStrToFunc);
        app.mount('#displaydiv')
        // const Component = Vue.extend(parseStrToFunc);
        // newcomponent.value.component = new Component().$mount();

        // display.value.appendChild(newcomponent.value.component.$el);
        // if (newcomponent.value.css !== "") {
        //     const style = document.createElement("style");
        //     style.type = "text/css";
        //     style.id = this.cssid;
        //     style.innerHTML = this.css;
        //     document.getElementsByTagName("head")[0].appendChild(style);
        // }
    }
}
onMounted(() => {

})
defineExpose({ renderCode })
</script>

<style lang="scss" scoped>
</style> 